package com.dtmiao.gulimall.product.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dtmiao.gulimall.common.utils.PageUtils;
import com.dtmiao.gulimall.common.utils.Query;

import com.dtmiao.gulimall.product.dao.PmsCategoryDao;
import com.dtmiao.gulimall.product.entity.PmsCategoryEntity;
import com.dtmiao.gulimall.product.service.PmsCategoryService;


@Service("pmsCategoryService")
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryDao, PmsCategoryEntity> implements PmsCategoryService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsCategoryEntity> page = this.page(
                new Query<PmsCategoryEntity>().getPage(params),
                new QueryWrapper<PmsCategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<PmsCategoryEntity> queryListTree() {
        List<PmsCategoryEntity> pmsCategoryEntities = baseMapper.selectList(null);

        List<PmsCategoryEntity> pmsCategoryEntityStream = pmsCategoryEntities.stream()
          .filter(pmsCategoryEntity -> pmsCategoryEntity.getParentCid() == 0).map((menu) -> {
            menu.setChildren(getTree(menu,pmsCategoryEntities));
            return menu;
            }).sorted((menu1,menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());}
            ).collect(Collectors.toList());

        return pmsCategoryEntityStream;
    }

    //递归查找二、三级菜单的方法
    public List<PmsCategoryEntity> getTree(PmsCategoryEntity root, List<PmsCategoryEntity> entities) {
        List<PmsCategoryEntity> collect = entities.stream().filter(pmsCategoryEntity -> pmsCategoryEntity.getParentCid() == root.getCatId())
                .map(pmsCategoryEntity -> {
                    pmsCategoryEntity.setChildren(getTree(pmsCategoryEntity, entities));
                    return pmsCategoryEntity;
                }).sorted((menu1, menu2) -> {
                            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                        }
                ).collect(Collectors.toList());
        return collect;

    }

}